import { createApp } from 'vue'
//@ts-ignore
import App from '@/App.vue'
import 'virtual:svg-icons-register'
// 引入自定义插件对象：注册整个项目全局组件
import globalComponent from '@/components/index'
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css'
import router from "@/router";
import pinia from '@/store';
import useUserStore from "@/store/modules/user";
//@ts-ignore
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

router.beforeEach(async (to, from, next) => {
    let userStore = useUserStore();
    let token = userStore.token;
    let userId = userStore.userId;
    if (token) {
        if (to.path === '/login') {
            next();
        }else{
            if(userId){
                await userStore.userInfo()
                next();
            } else {
                try {
                    await userStore.userInfo()
                    next();
                } catch (error) {
                    await userStore.userLogout()
                    next({ path: '/login', query: { redirect: to.path } })
                }
            }
        }

    } else {
            if (to.path == '/login' || to.path == '/register') {
                next()
            } else {
                next({ path: '/login', query: { redirect: to.path } })
            }
        }
});


//创建一个应用
const  app = createApp(App);
app.use(globalComponent)
//使用路由器
app.use(router);
//使用仓库
app.use(pinia);
//使用element-plus
app.use(ElementPlus, {
    locale: zhCn
})
//引入全局样式
import '@/styles/index.scss'
//挂载整个应用到app容器
app.mount('#app')
